import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/pages/drama_detail/drama_detail_state.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_taotaoshipin/model/video_geturl_entity.dart';
import 'package:flutter_taotaoshipin/player/flick_multi_player.dart';
import 'package:flutter_taotaoshipin/util/format_utils.dart';
import 'package:flutter_taotaoshipin/value/constant.dart';
import 'package:flutter_taotaoshipin/value/global_config.dart';
import 'package:flutter_taotaoshipin/widget/load_image.dart';
import 'package:get/get.dart';
import 'package:visibility_detector/visibility_detector.dart';

import 'drama_detail_controller.dart';

class DramaDetailPage extends StatefulWidget {
  const DramaDetailPage({super.key, this.tag});

  final String? tag;

  @override
  State<DramaDetailPage> createState() => _DramaDetailPageState();
}

class _DramaDetailPageState extends State<DramaDetailPage> {
  late DramaDetailController controller;
  late DramaDetailState state;

  @override
  void initState() {
    super.initState();

    controller =
        Get.find<DramaDetailController>(tag: widget.tag);
    state =
        Get.find<DramaDetailController>(tag: widget.tag).state;
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      value: SystemUiOverlayStyle.light,
      child: Scaffold(
        backgroundColor: Colors.black,
        body: VisibilityDetector(
          key: ObjectKey(controller.flickMultiManager),
          onVisibilityChanged: (visibility) {
            if (visibility.visibleFraction == 0 && mounted) {
              // 进入后台暂停播放
              controller.flickMultiManager.pause();
            }
          },
          child: SizedBox.expand(
            child: Stack(
              children: [
                _videoPlayer(),
                _videoAppBar(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  _videoPlayer() {
    return GetBuilder<DramaDetailController>(
      tag: widget.tag,
      id: 'dramaListEntityList',
      builder: (controller) {
        if (state.dramaListEntityList.isEmpty) {
          return Container();
        } else {
          if (state.mainInfoEntity?.isSelf != 1) {
            // 穿山甲短剧
            List<Widget> children = [
              // Container(
              //   decoration: BoxDecoration(),
              //   clipBehavior: Clip.hardEdge,
              //   child: UiKitView(
              //     viewType: TtspPangrowthConstants.playletTypeId,
              //     layoutDirection: TextDirection.ltr,
              //     onPlatformViewCreated:
              //         controller.onPangrowthPlayletViewCreate,
              //     creationParams: <String, dynamic>{
              //       'skitId': state
              //           .dramaListEntityList[state.pageIndex]
              //           .vid,
              //       'episode': state.pageIndex + 1,
              //       'bottomOffset': !showNativeAd()
              //           ? 0
              //           : Constant.adBannerHeight,
              //     },
              //     creationParamsCodec: const StandardMessageCodec(),
              //   ),
              // ),
            ];
            children.addAll([
              Positioned(
                  right: 20,
                  bottom: !showNativeAd() ? 200 : 240,
                  child: _buildRights()),
              Positioned(
                  left: 0,
                  right: 0,
                  bottom: !showNativeAd()
                      ? 40
                      : Constant.adBannerHeight + 40,
                  child: _buildInfos()),
              Positioned(
                  left: 0, bottom: 0, right: 0, child: _buildBottoms()),
            ]);

            return Stack(
              alignment: Alignment.center,
              children: children,
            );
          } else {
            return PageView.builder(
              physics: const ClampingScrollPhysics(),
              controller: controller.pageController,
              scrollDirection: Axis.vertical,
              onPageChanged: controller.onPageChanged,
              itemCount: Constant.isFree
                  ? state.userDramaAuthListEntityList.length
                  : state.dramaListEntityList.length,
              itemBuilder: (context, index) {
                return FutureBuilder<VideoGeturlEntity?>(
                  future: controller.fullLoadVideoUrlData(index),
                  builder: (context, snapshot) {
                    List<Widget> children;
                    if (snapshot.hasData) {
                      children = <Widget>[
                        FlickMultiPlayer(
                          url: snapshot.data!.vodPlayInfo!.mainPlayUrl!,
                          flickMultiManager:
                              controller.flickMultiManager,
                          progressBarBottomOffset: !showNativeAd()
                              ? 0
                              : Constant.adBannerHeight,
                          onVideoEnd: () {
                            int length = Constant.isFree
                                ? state
                                    .userDramaAuthListEntityList.length
                                : state.dramaListEntityList.length;
                            if (index + 1 >= length) {
                              EasyLoading.showToast('播放完毕');
                            } else {
                              /// 播放完成跳转下一页
                              controller.pageController.nextPage(
                                duration: const Duration(milliseconds: 300),
                                curve: Curves.easeInOut,
                              );
                            }
                          },
                        ),
                      ];
                    } else if (snapshot.hasError) {
                      children = <Widget>[
                        const Icon(
                          Icons.error_outline,
                          color: Colors.red,
                          size: 60,
                        ),
                        Padding(
                          padding: const EdgeInsets.only(top: 16),
                          child: Text('Error: ${snapshot.error}'),
                        ),
                      ];
                    } else {
                      children = <Widget>[
                        const CircularProgressIndicator(),
                      ];
                    }
                    children.addAll([
                      Positioned(
                          right: 20,
                          bottom: !showNativeAd() ? 200 : 240,
                          child: _buildRights()),
                      Positioned(
                          left: 0,
                          right: 0,
                          bottom: !showNativeAd()
                              ? 30
                              : Constant.adBannerHeight + 30,
                          child: _buildInfos()),
                      Positioned(
                          left: 0,
                          bottom: 0,
                          right: 0,
                          child: _buildBottoms()),
                    ]);

                    return Stack(
                      alignment: Alignment.center,
                      children: children,
                    );
                  },
                );
              },
            );
          }
        }
      },
    );
  }

  /// 视频详情页appbar
  _videoAppBar() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 15),
      child: SafeArea(
        bottom: false,
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            if (state.showBackBtn)
              Positioned(
                left: 15,
                child: InkWell(
                  onTap: () {
                    Get.back();
                  },
                  child: Row(
                    children: [
                      const Icon(
                        Icons.arrow_back_ios_new,
                        color: Colors.white,
                        size: 16,
                      ),
                      SizedBox(width: 5),
                      GetBuilder<DramaDetailController>(
                        tag: widget.tag,
                        id: 'pageIndex',
                        builder: (controller) {
                          return Text(
                            '第${controller.state.pageIndex + 1}集',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16,
                              fontWeight: FontWeight.w400,
                            ),
                          );
                        },
                      ),
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  _buildInfos() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 16, 26, 26),
      child: Row(
        children: [
          Expanded(
            child: Text(
              state.mainInfoEntity?.title ?? '',
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w400,
                color: Colors.white,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          // GestureDetector(
          //   onTap: () {
          //     controller.enterFullScreen();
          //   },
          //   child: LoadAssetImage(
          //     'drama/detail/fullscreen',
          //     width: 34,
          //     height: 34,
          //   ),
          // ),
        ],
      ),
    );
  }

  _buildRights() {
    return GetBuilder<DramaDetailController>(
        tag: widget.tag,
        id: 'dramaInteractInfoEntity',
        builder: (controller) {
          return Column(
            children: [
              _buildRightItem(
                imageName:
                    (state.dramaInteractInfoEntity.collectBool ??
                            false)
                        ? 'drama/detail/collect_sel'
                        : 'drama/detail/collect',
                text: (state.dramaInteractInfoEntity.collectBool ??
                        false)
                    ? '已追'
                    : '追剧',
                onTap: () {
                  controller.userCollectBtnClicked();
                },
              ),
              GetBuilder<AppController>(builder: (appController) {
                var text = countFormat(
                    state.dramaInteractInfoEntity.share ?? 0);
                return Visibility(
                  visible: GlobalConfig.isReview == 0,
                  child: Padding(
                    padding: EdgeInsets.only(top: 26),
                    child: _buildRightItem(
                      imageName: 'drama/detail/share',
                      text: '分享',
                      onTap: () {
                        appController.appProfile.shareBtnClicked =
                            true;
                        appController.updateAppProfile(
                            appController.appProfile);
                        controller.userShareBtnClicked();
                      },
                      isRed: !appController
                          .appProfile.shareBtnClicked!,
                    ),
                  ),
                );
              }),
              SizedBox(height: 26),
              GetBuilder<AppController>(builder: (appController) {
                var text = countFormat(
                    state.dramaInteractInfoEntity.share ?? 0);
                return _buildRightItem(
                  imageName: 'drama/detail/episodes',
                  text: '选集',
                  onTap: () {
                    controller.episodeButClicked();
                  },
                );
              }),
            ],
          );
        });
  }

  _buildRightItem({
    required String imageName,
    String? text,
    Function()? onTap,
    bool isRed = false,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        child: Stack(
          children: [
            Column(
              children: [
                LoadAssetImage(
                  imageName,
                  width: 34,
                ),
                if (text != null)
                  Padding(
                    padding: const EdgeInsets.only(top: 3),
                    child: Text(
                      text,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
              ],
            ),
            if (isRed)
              Positioned(
                top: 0,
                right: 0,
                child: Container(
                  width: 8,
                  height: 8,
                  decoration: BoxDecoration(
                    color: Colors.red,
                    borderRadius: BorderRadius.circular(5),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  _buildBottoms() {
    if (!showNativeAd()) {
      return Container();
    } else {
      return Container(
        color: Colors.black,
        child: Column(
          children: [
            Container(
              height: Constant.adBannerHeight,
              child: Row(
                children: [
                  // _buildAdBanner(),
                ],
              ),
            ),
            Container(
              width: double.infinity,
              height: MediaQuery.of(context).padding.bottom,
              color: Colors.black,
            ),
          ],
        ),
      );
    }
  }

  // _buildAdBanner() {
  //   AppController appController = Get.find();
  //   var nativeAd = appController.csj.list
  //       ?.firstWhereOrNull((element) => element.adverType == '3');
  //   if (!isVip() && nativeAd != null) {
  //     if (defaultTargetPlatform == TargetPlatform.iOS) {
  //       double width = Get.mediaQuery.size.width;
  //       double height = Constant.adBannerHeight;
  //       return Container(
  //         width: width,
  //         height: height,
  //         decoration: BoxDecoration(color: Colors.transparent),
  //         clipBehavior: Clip.hardEdge,
  //         child: UiKitView(
  //           viewType: TtspGromoreConstant.nativeAdViewId,
  //           layoutDirection: TextDirection.ltr,
  //           creationParams: {
  //             'id': nativeAd.adverId,
  //             'width': width.toString(),
  //             'height': height.toString(),
  //             'type': 'banner',
  //             'index': '0',
  //           },
  //           creationParamsCodec: const StandardMessageCodec(),
  //         ),
  //       );
  //     } else {
  //       return Container();
  //     }
  //   } else {
  //     return Container();
  //   }
  // }
}
